package com.scnu409.mimicontact;

import com.scnu409.mimicontact.R;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class RefreshListView extends ListView implements OnScrollListener {

	/*
	 * @param header 顶部布局view
	 * 
	 * @param footer 底部布局view
	 */
	View header;
	View footer;

	private int _headerHeight;
	private int _firstVisiableItme;// 第一个可见的Item

	/*
	 * 滑动的四个状态
	 */
	private static final int NONE = 0;
	private static final int PULL = 1; // 提示下拉状态
	private static final int RELEASE = 2; // 提示释放状态
	private static final int REFLASHING = 3; // 提示正在刷新状态
	private int state;

	/*
	 * 只有最开始的位置才可以下拉跟新，其余的只有滑动
	 */
	private boolean isRecored;
	private int startY;// 开始的位置
	private int scrollState;// 下拉的状态

	public RefreshListView(Context context) {
		super(context);
		initView(context);
	}

	public RefreshListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	public RefreshListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView(context);
	}

	/**
	 * 初始化界面
	 * 
	 * @param context
	 */
	private void initView(Context context) {
		/*
		 * 获取顶部布局文件
		 */
		LayoutInflater inflater = LayoutInflater.from(context);
		header = inflater.inflate(R.layout.header_layout, null);
		footer = inflater.inflate(R.layout.footer_layout, null);

		/*
		 * 把顶部布局文件添加到此ListView中 把底部布局文件添加到ListView中
		 */

		mesuerHeight(header);
		mesuerHeight(footer);
		_headerHeight = header.getMeasuredHeight();
		topPadding(-_headerHeight);
		Log.i("tag", "_headerHeight=" + _headerHeight);
		this.addHeaderView(header);
		this.addFooterView(footer);
		this.setOnScrollListener(this);
	}

	/*
	 * 设置ListView向上隐藏
	 */
	private void topPadding(int topPadding) {
		header.setPadding(header.getPaddingLeft(), topPadding,
				header.getPaddingRight(), header.getPaddingBottom());
		header.invalidate();// 重新绘制
	}

	/*
	 * @param view 测量的view 测量view的高度 ，用于告诉父布局，此view占多大地方
	 */
	private void mesuerHeight(View view) {
		// 获取view 的布局
		ViewGroup.LayoutParams p = view.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}

		// 获取子布局的宽度
		int width = ViewGroup.getChildMeasureSpec(0, 0, p.width);
		int height;
		int temHeight = p.height;
		if (temHeight > 0) {
			// 高度不空，需要填充这个布局
			height = MeasureSpec
					.makeMeasureSpec(temHeight, MeasureSpec.EXACTLY);
		} else
			height = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);

		view.measure(width, height);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		this.scrollState = scrollState;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @param firstVisibleItem 第一个可见的Item
	 */
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this._firstVisiableItme = firstVisibleItem;
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {

		Log.i("tag", "touchEvent");
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			Log.i("tag", "touchEven_Down");
			if (_firstVisiableItme == 0) {
				isRecored = true;
				startY = (int) ev.getY();
			}
			break;
		case MotionEvent.ACTION_MOVE:
			Log.i("tag", "touchEven_MOVE");
			onMove(ev);
			break;
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP:
			Log.i("tag", "touchEven_Up");
			onMove(ev);
			if (state == RELEASE) {
				state = REFLASHING;
				refershViewByState();
			} else if (state == PULL) {
				state = NONE;
				refershViewByState();
			}
			break;
		}

		return super.onTouchEvent(ev);

	}// onTouchEvent事件结束

	// 滑动的事件
	private void onMove(MotionEvent ev) {

		if (!isRecored)
			return;

		int temY = (int) ev.getY();
		int space = temY - startY;
		// 下拉时一直改变topPaddin
		int topPadding = space - _headerHeight;
		switch (state) {
		case NONE:
			if (space > 0)
				state = PULL; // 如果开始下拉，但没有超过header的高度，状态改变为PILL
			refershViewByState();
			break;
		case PULL:
			topPadding(topPadding);
			if (space > _headerHeight + 30
					&& scrollState == SCROLL_STATE_TOUCH_SCROLL)// 如果下拉的高度高于header的高度，切实滚动状态
			{
				Log.i("tag", "pull_height");
				state = RELEASE;
				refershViewByState();
			} else {
				state = NONE;
				Log.i("tag", "pull_low");
				refershViewByState();
			}
			break;
		case RELEASE:
			topPadding(topPadding);
			if (space < _headerHeight + 30) {
				state = PULL;
				refershViewByState();
			} else if (space <= 0) {
				state = NONE;
				refershViewByState();
			}

			break;
		case REFLASHING:
			topPadding(topPadding);
			refershViewByState();
			break;
		}
	}

	// 下拉过程中，改变组件的状态
	private void refershViewByState() {

		// 下拉跟新中的组件
		TextView refreshAble = (TextView) findViewById(R.id.refresh_able);
		TextView tip = (TextView) findViewById(R.id.tip);
		if (tip == null)
			Log.i("tag", "tip is null");
		ImageView refreshImg = (ImageView) findViewById(R.id.refresh_img);
		ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
		if (progressBar != null)
			Log.i("tag", "progressBar is not null");
		else
			Log.i("tag", "progressBar is null");

		// 旋转的动漫
		RotateAnimation anim1 = new RotateAnimation(0, 180,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		anim1.setDuration(500);
		anim1.setFillAfter(true);
		RotateAnimation anim2 = new RotateAnimation(180, 0,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		anim2.setDuration(500);
		anim2.setFillAfter(true);

		switch (state) {
		case NONE:
			topPadding(-_headerHeight);
			progressBar.setVisibility(View.GONE);
			break;

		case PULL:
			refreshImg.setVisibility(View.VISIBLE);
			progressBar.setVisibility(View.GONE);
			refreshAble.setText("下拉可以跟新");
			// 这里从SharedPreference中获取上次跟新的时间
			tip.setText("上次跟新时间是");
			tip.setVisibility(View.VISIBLE);
			refreshImg.clearAnimation();
			refreshImg.setAnimation(anim1);

			break;
		case RELEASE:
			progressBar.setVisibility(View.GONE);
			refreshImg.setVisibility(View.VISIBLE);
			refreshImg.clearAnimation();
			refreshImg.setAnimation(anim2);
			break;
		case REFLASHING:
			topPadding(50);
			progressBar.setVisibility(View.VISIBLE);
			refreshImg.setVisibility(View.GONE);
			tip.setText("正在刷新");
			refreshAble.setVisibility(View.GONE);
			refreshImg.clearAnimation();
			break;
		}
	}
}
